﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Udp;
using UtilZ.Dotnet.Ex.Log;

namespace DotnetWinFormApp
{
    public partial class FTestBroadcast : Form
    {
        public FTestBroadcast()
        {
            InitializeComponent();
        }

        private void FTestBroadcast_Load(object sender, EventArgs e)
        {
            var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
            if (redirectAppenderToUI != null)
            {
                redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
            }
        }

        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            logControl1.AddLog(e.Item.Content, e.Item.Level);

            //string str;
            //try
            //{
            //    str = string.Format("{0} {1}", DateTime.Now, e.Item.Content);
            //}
            //catch (Exception ex)
            //{
            //    str = ex.Message;
            //}

            //logControl.AddLog(str, e.Item.Level);
        }



        private NetUdpClient _muiltBroadcastRcv = null;
        private void btnRev_Click(object sender, EventArgs e)
        {
            try
            {
                var unpacker = new NetUDPUnpacker();
                unpacker.PackOutput += _unpacker_PackOutput;

                var initPara = new NetUdpClientInitPara(unpacker, new IPEndPoint(IPAddress.Any, 1900))
                {
                    Transfer = UDPTransferMode.Multicast,
                    Multicast = MulticastMode.Receive,
                    MulticastIPAddress = IPAddress.Parse("239.255.255.250"),
                    Ttl = 1,
                };
                this._muiltBroadcastRcv = new NetUdpClient(initPara);
                this._muiltBroadcastRcv.Start();

                Loger.Info("已开启组播监听");
            }
            catch (Exception ex)
            {
                Loger.Error(ex, "开启监听组播异常");
            }
        }

        private void _unpacker_PackOutput(object sender, DataOutputArgs e)
        {
            var netLinkInfo = (NetLinkInfo)e.LinkInfo;
            string localEPStr = NetHelper.GetIPPortString(netLinkInfo.LocalEndPoint);
            string remoteEPStr = NetHelper.GetIPPortString(netLinkInfo.RemoteEndPoint);
            string json = Encoding.UTF8.GetString(e.Data.Bytes, e.Data.Offset, e.Data.Length);
            Loger.Info($"收到组播消息:{remoteEPStr}->{localEPStr}:\r\n{json}");
        }



        private NetUdpClient _muiltBroadcastSend = null;
        private IPEndPoint _dstEndPoint;
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._muiltBroadcastSend == null)
                {
                    var unpacker = new NetUDPUnpacker();
                    unpacker.PackOutput += _unpacker_PackOutput;

                    var initPara = new NetUdpClientInitPara(unpacker, new IPEndPoint(IPAddress.Any, 2900))
                    {
                        Transfer = UDPTransferMode.Multicast,
                        Multicast = MulticastMode.Send,
                        MulticastIPAddress = IPAddress.Parse("239.255.255.250"),
                        Ttl = 1,
                    };
                    this._muiltBroadcastSend = new NetUdpClient(initPara);
                    this._dstEndPoint = new IPEndPoint(initPara.MulticastIPAddress, 1900);
                    this._muiltBroadcastSend.Start();
                }


                string json = $"{TimeEx.GetTimestamp()}请求建立连接";
                byte[] buffer = Encoding.UTF8.GetBytes(json);
                this._muiltBroadcastSend.SendTo(buffer, this._dstEndPoint);
                Loger.Info($"{NetHelper.GetIPPortString(this._dstEndPoint)}发送组播成功");

            }
            catch (Exception ex)
            {
                Loger.Error(ex, "发送广播异常");
            }
        }


        private UdpClient _udpClient = null;
        private void btnSend2_Click(object sender, EventArgs e)
        {
            // 组播地址和端口
            string multicastAddress = "239.255.255.250"; // 组播地址
            int multicastPort = 1900; // 组播端口

            if (_udpClient == null)
            {
                _udpClient = new UdpClient();     // 创建UdpClient实例
                // 设置TTL（Time To Live），控制数据包在网络中的传播范围
                _udpClient.Ttl = 1; // TTL=1表示数据包只能在本地网络传播
            }


            // 要发送的消息
            string message = "Hello, Multicast!";
            byte[] buffer = Encoding.UTF8.GetBytes(message);

            // 创建组播目标地址
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(multicastAddress), multicastPort);

            // 发送数据到组播地址
            _udpClient.Send(buffer, buffer.Length, endPoint);

            Console.WriteLine($"Sent: {message} to {multicastAddress}:{multicastPort}");
        }
    }
}
